package com.moon.interface_api.controller;


import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 *Created by chengliang on 2018/8/27.
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

    @Value("${upload.src}")
    private  String src;//图片访问地址
    @Value("${upload.img}")
    private  String imgUrl;//图片存储地址
    @Value("${upload.file}")
    private  String fileUrl;//文档存储地址

    
    @RequestMapping("/upload")
    @ResponseBody
    public String uploadPic(@RequestParam MultipartFile pic, HttpServletRequest request) throws IllegalStateException, IOException {
        try {
            // 获取图片原始文件名
            String originalFilename = pic.getOriginalFilename();
            // 文件名使用当前时间
            String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            // 获取上传图片的扩展名(jpg/png/...)
            String extension = FilenameUtils.getExtension(originalFilename);
            // 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
            //String path = request.getContextPath();
            //String path = request.getServletContext().getRealPath("/");
            String path;
            //判断文件类型，分别存入不同文件夹
            if ("jpg".equals(extension) || "png".equals(extension)) {
                path = imgUrl;
            } else if ("txt".equals(extension) || "pdf".equals(extension)) { 
                path = fileUrl;
            } else {
                throw new RuntimeException("上传文件格式不正确！");
            }
            String fileName = name + "." + extension;
            //图片上传的绝对路径
            String url = path;
            File dir = new File(url);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 上传图片
            pic.transferTo(new File(url + "/" + fileName));
            return src+"/"+fileName;
        } catch (Exception e) {
            String message = e.getMessage();
            throw new RuntimeException("服务器繁忙，上传图片失败");
        }
    }

}
